package com.llkj.qingnianguoxue.circle;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.InterestCircleAdapter;
import com.llkj.qingnianguoxue.base.BaseFragment;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.CircleListBean;
import com.llkj.qingnianguoxue.bean.EventChangeUserBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.util.ClickViewCallback;
import com.llkj.qingnianguoxue.util.DialogUtil;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.PayMethodViewUtil;
import com.llkj.qingnianguoxue.util.RxBus;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.functions.Action1;

/**
 * 兴趣圈
 */
public class InterestCircleFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener,PayMethodViewUtil.PaySuccessListener  {
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView lvActions;
    private InterestCircleAdapter interestCircleAdapter;
    private List<CircleListBean.CircleBean> mCircleData;
    private int totalSize, mPage,mCurrentPosition;
    private PayMethodViewUtil payMethodViewUtil;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_interest_circle, container, false);
        EventBus.getDefault().register(this);
        initView();
        initListener();

        loadWaitDialog();
        onRefresh();
        return rootView;
    }

    private void initView(){
        refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh_layout);
        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
        lvActions = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        lvActions.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

        mCircleData = new ArrayList<>();
        interestCircleAdapter = new InterestCircleAdapter(R.layout.item_interest_circle,mCircleData,null);
        interestCircleAdapter.setType(1);
        lvActions.setAdapter(interestCircleAdapter);

        payMethodViewUtil = new PayMethodViewUtil(this,this);

    }
    private void initListener(){
        refreshLayout.setOnRefreshListener(this);
        interestCircleAdapter.setOnLoadMoreListener(this);
        RxBus.getInstance().toObservable(String.class).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                if (s.equals(ConstantUserInfo.REFRESH_CIRCLE)){
                    onRefresh();
                }
            }
        });
        lvActions.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                Bundle bundle = new Bundle();
                bundle.putString("circleId",mCircleData.get(i).getId());
                startActivity(CircleDetailActivity.class,bundle);
            }
        });
        lvActions.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                clickViewCallback(i);
            }
        });
    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        startActivity(LoginActivity.class);
    }

    private void clickViewCallback(int position) {
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        if (!isLogin) {
            dialogConfirm(null, null, null, null).show();
            return;
        }
        //稍后处理，需在支付完成后
        mCurrentPosition = position;
        final CircleListBean.CircleBean circleBean = mCircleData.get(mCurrentPosition);
        String note = "加入圈子需支付"+circleBean.getPrice()+"元\n费用时限"+circleBean.getCycle()+"天";
        DialogUtil.dialogConfirm(getActivity(), note, null, "考虑一下", "支付", new DialogUtil.DialogClickListener() {
            @Override
            public void dialogClick(int type) {
                if(type==1){
                    payMethodViewUtil.showPayMethodDialog(circleBean.getPrice());
                }
            }
        }).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        payMethodViewUtil.onActivityResult(requestCode, resultCode, data);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeUser(EventChangeUserBean event){
        onRefresh();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onLoadMore() {
        mPage++;
        getCircleData();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getCircleData();
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, interestCircleAdapter, null, lvActions, totalSize);
    }

    /**
     * 获取圈子数据
     */
    private void getCircleData(){
        HttpMethod.circleIndex(getActivity(),this,"1", String.valueOf(mPage));
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if(method == HttpMethod.HTTP_CIRCLE_INDEX){
            CircleListBean circleListBean = GsonUtil.GsonToListBean(data,CircleListBean.class);
            if(circleListBean != null){
                totalSize = Integer.parseInt(circleListBean.getNum());
                if (mPage == 1) {
                    mCircleData.clear();
                    LoadDataHelper.refreshComplete(interestCircleAdapter, mCircleData, refreshLayout, lvActions);
                } else {
                    interestCircleAdapter.setEnableLoadMore(true);
                    interestCircleAdapter.loadMoreComplete();
                }
                if(circleListBean.getList()!=null){
                    mCircleData.addAll(circleListBean.getList());
                }

                interestCircleAdapter.notifyDataSetChanged();
            }
        }else if(method == HttpMethod.HTTP_CIRCLE_ADD_GROUP){//6.4加入圈子
            ToastUtil.makeLongText(getActivity(),"加入成功");
            CircleListBean.CircleBean circleBean = mCircleData.get(mCurrentPosition);
            circleBean.setIs_add("1");
            interestCircleAdapter.notifyItemChanged(mCurrentPosition);
//            RxBus.getInstance().post(ConstantUserInfo.REFRESH_CIRCLE);
        }
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        super.onhttpFailed(message, method);
        if (!StringUtils.isEmpty(message)) {
            ToastUtil.makeShortText(mActivity, message);
        }
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void paySucessResponse(int type) {
        //处理三方支付成功后的操作
        CircleListBean.CircleBean item = mCircleData.get(mCurrentPosition);
        loadWaitDialog();
        HttpMethod.addGroup(getActivity(),this,item.getHx_id(),item.getPrice(),item.getCycle(),item.getId(),String.valueOf(type));
    }
}
